package com.eqdd.yiqidian.ui.mine.pizhun;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.eqdd.yiqidian.NoticeInfoActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.LeaveCheckerListResultBean;
import com.eqdd.yiqidian.bean.rebuild.LeaveInfoResultBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditHintBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.select.ShowRichTextActivity;
import com.eqdd.yiqidian.utils.DateUtil;
import com.eqdd.yiqidian.utils.RichTextUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.functions.BiFunction;
import io.reactivex.subscribers.DisposableSubscriber;

public class LeaveInfoActivity extends BaseActivity {
    private NoticeInfoActivityCustom dataBinding;
    private SlimAdapterEx<SlimEditBean> slimAdapterEx;
    private String leaveId;
    private ArrayList<SlimEditBean> datas;
    private int type;
    private LeaveInfoResultBean items;
    private List<LeaveCheckerListResultBean> checkers;
    private int who;
    private int status;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_notice_info);
        initTopTitleBar(View.VISIBLE, "请假详情");
    }

    @Override
    public void initData() {
        leaveId = getIntent().getStringExtra("leaveId");
        who = getIntent().getIntExtra(Config.WHO, 0);
        status = getIntent().getIntExtra(Config.STATUS, 0);
        initTitle();
        datas = new ArrayList<>();
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterEx = SlimAdapterEx.create()
                .register(R.layout.list_item_29, new SlimInjector<SlimEditEnterBean>() {
                    @Override
                    public void onInject(SlimEditEnterBean data, IViewInjector injector) {
                        injector
                                .text(R.id.tv_left_content, dealText(data.getTitle()))
                                .text(R.id.tv_right_content, dealText(data.getContent()))
                                .with(R.id.tv_right_content, v -> ((TextView) v).setHint(dealText(data.getHintContent())));
                    }
                })
                .register(R.layout.list_item_28, new SlimInjector<SlimEditHintBean>() {
                    @Override
                    public void onInject(SlimEditHintBean data, IViewInjector injector) {
                        injector.text(R.id.tv_left_content, dealText(data.getTitle()))
                                .text(R.id.tv_right_hint_content, dealText(data.getContent()));
                    }
                }).attachTo(dataBinding.recyclerView);
        dataBinding.rbReject.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                dataBinding.rbAgree.setChecked(!isChecked);
            }
        });
        dataBinding.rbAgree.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                dataBinding.rbReject.setChecked(!isChecked);
            }
        });
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    switch (slimAdapterEx.getDataItem(position).getPosition()) {
                        case 9:
                            Bundle bundle = new Bundle();
                            bundle.putString(Config.TITLE, "原因");
                            bundle.putSerializable(Config.RICH_TEXT_RESULT, RichTextUtil.getRichText(items.getLeaveReason(), items.getNewImages()));
                            startActivity(ShowRichTextActivity.class, bundle);
                            break;
                    }
                });
    }

    private void initTitle() {
        if (who >= 1 && status == 0) {
            initTopRightText("提交", v -> {
                if (checkParam()) {
                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + (who == 2 ? HttpConfig.LEAVE_CHECK_BY_HR : HttpConfig.LEAVE_CHECK))
                            .params("leaveId", items.getId())
                            .params("userGuid", user.getGuid())
                            .params("message", getText(dataBinding.etRemark))
                            .params("type", dataBinding.rbAgree.isChecked() ? 1 : 2)
                            .execute(new DialogCallBack<HttpResult>(this) {
                                @Override
                                public void onSuccess(Response<HttpResult> response) {
                                    HttpResult httpResult = response.body();
                                    ToastUtil.showShort(httpResult.getMsg());
                                    if (httpResult.getStatus() == 200) {
                                        setResult(Config.SUCCESS);
                                        finish();
                                    }
                                }
                            });
                } else {
                    ToastUtil.showLong("真残忍，能否给个理由先？");
                }
            });
        }
    }

    private boolean checkParam() {
        return !(dataBinding.rbReject.isChecked() && TextUtils.isEmpty(dataBinding.etRemark.getText()));
    }

    @Override
    public void setView() {
        Flowable<HttpResult<List<LeaveCheckerListResultBean>>> flowLeaveChecker = OkGo.<HttpResult<List<LeaveCheckerListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.LEAVE_CHECKER_LIST)
                .params("leaveId", this.leaveId)
                .converter(new JsonConverter<HttpResult<List<LeaveCheckerListResultBean>>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<List<LeaveCheckerListResultBean>>>());

        Flowable<HttpResult<LeaveInfoResultBean>> flowLeaveInfo = OkGo.<HttpResult<LeaveInfoResultBean>>post(HttpConfig.BASE_URL + HttpConfig.LEAVE_INFO)
                .params("leaveId", this.leaveId)
                .converter(new JsonConverter<HttpResult<LeaveInfoResultBean>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<LeaveInfoResultBean>>());
        Flowable.combineLatest(flowLeaveChecker, flowLeaveInfo, (BiFunction<HttpResult<List<LeaveCheckerListResultBean>>, HttpResult<LeaveInfoResultBean>, Object>) (listHttpResult, leaveInfoResultBeanHttpResult) -> {
            if (leaveInfoResultBeanHttpResult.getStatus() == 200) {
                items = leaveInfoResultBeanHttpResult.getItems();
                if (items == null) {
                    if (!dispos.isDisposed()) {
                        dispos.dispose();
                    }
                    ToastUtil.showShort("单子已删除");
                    finish();
                }
            }
            if (listHttpResult.getStatus() == 200) {
                checkers = listHttpResult.getItems();

            }
            return 1;
        })
                .subscribe(dispos);

    }

    private DisposableSubscriber dispos = new DisposableSubscriber() {
        @Override
        public void onNext(Object o) {
            datas.add(new SlimEditHintBean("编码", items.getLeaveCode(), 0));
            datas.add(new SlimEditHintBean("请假人", items.getStaffName(), 1));
            datas.add(new SlimEditHintBean("公司", items.getCompany(), 2));
            datas.add(new SlimEditHintBean("部门", items.getDepartment(), 3));
            datas.add(new SlimEditHintBean("职位", items.getPost(), 4));
            datas.add(new SlimEditHintBean("工号", items.getJobNumber(), 5));
            datas.add(new SlimEditHintBean("请假天数", items.getLeaveTimes() + "天", 6));
            datas.add(new SlimEditHintBean("请假时间", items.getLeaveStartTime() + "~" +
                    items.getLeaveEndTime(), 7));
            datas.add(new SlimEditHintBean("离职类型", items.getLeaveType(), 8));
            datas.add(new SlimEditEnterBean("原因", items.getLeaveReason(), 9, true, ""));
            for (LeaveCheckerListResultBean checker : checkers) {
                datas.add(new SlimEditHintBean("审批人 " + checker.getUname(),
                        checker.getStatus() == -1 ? "等待审核" : checker.getStatus() == 2 ? "已拒绝" : "已同意", 10));
            }
            slimAdapterEx.updateData(datas);
            if (type == 1) {
                dataBinding.llDownRoot.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onError(Throwable t) {
            System.out.println("LeaveInfoActivity->onError" + t.toString());
        }

        @Override
        public void onComplete() {

        }
    };

    private String dealText(String text) {
        return TextUtils.isEmpty(text) ? "" : text;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }
}
